//
// Copyright (c) 2014, 保留所有权利。
//
// TradeSync.java
//
// 作    者：王红燕
// 当前版本：1.0
// 2014 下午1:15:59
//
// 
//
package com.vanke.agent.sync;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;


import org.apache.log4j.Logger;

import com.vanke.agent.ADataSource;
import com.vanke.agent.C;
import com.vanke.agent.common.CstUtil;

/**
 *
 */
public class ProjectSync extends AgentSync {
	Logger log = Logger.getLogger(ProjectSync.class);
	String table = "p_Project";
	String fields = C.FIELDS_PROJECT;

	@Override
	public void sync() {
		log.info("=============sync new p_Project===========");
		Connection con = ADataSource.getConnection(ADataSource.SCHEMA_MY);
		Connection wcon = ADataSource.getConnection(ADataSource.SCHEMA_BIZ);

		try {

			String querySql = "SELECT " + fields + "  FROM " + table;
			log.info("execute: " + querySql);
			PreparedStatement pstmt = con.prepareStatement(querySql,
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			ResultSet rs = pstmt.executeQuery();
			int count = 0;
			if (!rs.next()) {
				log.info("no project is created");
				ADataSource.close(rs);
				ADataSource.close(pstmt);
				return;
			}

			String insertSql = CstUtil.formatInsertSql(table, fields
					+ ",LastModifyTime,status");
			PreparedStatement wpstmt = wcon.prepareStatement(insertSql);
			int columns = fields.split(",").length;
			
			String updateFields = fields.replaceAll(" ", "").replace("BUGUID,", "");
			String updateSql = CstUtil.formatUpdateSql(table, updateFields + ",LastModifyTime,status");
			updateSql += " where ProjGUID =?";
			log.info("execute update : " + updateSql);
			PreparedStatement dataUpdatePs = wcon.prepareStatement(updateSql);
			String[] updateColumnds = updateFields.split(",");

			PreparedStatement dataps = wcon.prepareStatement(querySql,
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			ResultSet datars = dataps.executeQuery();
			Map<String, Boolean> dataGuidMap = new HashMap<String, Boolean>();
			while (datars.next()) {
				dataGuidMap.put(datars.getString("ProjGUID").trim(), true);
			}

			Map<String, Boolean> myErpGuidMap = new HashMap<String, Boolean>();

			do {
				myErpGuidMap.put(rs.getString("ProjGUID").trim(), true);
				try {
					if (dataGuidMap
							.containsKey(rs.getString("ProjGUID").trim())) {
						int len = updateColumnds.length;
						for (int i = 1; i <= len; i++) {
							dataUpdatePs.setString(i, rs.getString(updateColumnds[i-1]));
						}
						dataUpdatePs.setTimestamp(len+1, new Timestamp(
								new java.util.Date().getTime()));
						dataUpdatePs.setInt(len+2, 1);
						dataUpdatePs.setString(len+3, rs.getString("ProjGUID"));
						dataUpdatePs.executeUpdate();
					} else {
						for (int i = 1; i <= columns; i++) {
							wpstmt.setString(i, rs.getString(i));
						}
						wpstmt.setTimestamp(34, new Timestamp(
								new java.util.Date().getTime()));
						wpstmt.setInt(35, 1);
						wpstmt.executeUpdate();
						log.info("project " + rs.getString("ProjGUID")
								+ " is added.");
					}
					count++;
				} catch (Exception e) {
					e.printStackTrace();
					log.error(e);
				}

				// TODO 通知消息

			} while (rs.next());

			String delSql = "update p_Project set status =0 where ProjGUID =? ";
			PreparedStatement delPs = wcon.prepareStatement(delSql);
			log.info("execute update delete flag : " + delSql);
			/** 标记删除的记录 **/
			for (String key : dataGuidMap.keySet()) {
				if (!myErpGuidMap.containsKey(key)) {
					log.info("project " + key + " is flag to delete.");
					delPs.setString(1, key);
					delPs.executeUpdate();
				}
			}

			// 关闭
			ADataSource.close(rs);
			ADataSource.close(datars);
			ADataSource.close(pstmt);
			ADataSource.close(wpstmt);
			ADataSource.close(dataUpdatePs);
			ADataSource.close(dataps);
			ADataSource.close(delPs);

			log.info(count + " project save or update ");
			log.info("=============sync project end===========");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(con);
			ADataSource.close(wcon);
		}
	} // ~sync
}
